// 导出的 时候，是 connections.promise()  所以下面不需要写 .promise().execute()
const connection = require('../app/database')
class MomentService {
  // 发布动态
  async create(userId, content) {
    const statement = `INSERT INTO moment (content, user_id) VALUES (?, ?);`;
    const [result] = await connection.execute(statement, [content, userId]);
    return result;
  }
  // 获取某一个动态
  async getMonentById(momentId) {
    const statement = `SELECT * FROM moment WHERE id = ?;`;
    const [result] = await connection.execute(statement, [momentId]);
    return result[0];
  }
  // 获取 所有 的 动态
  async getMonentList(size, offset) {
    const statement = `
      SELECT
        m.id id, m.content content, m.createAt createTime, m.updateAt updateTime,
        JSON_OBJECT('id',u.id,'name',u.name) author
      FROM moment m
      LEFT JOIN user u ON m.user_id = u.id
      LIMIT ? OFFSET ?;
    `
    const [result] = await connection.execute(statement, [size, offset]);
    console.log(result);
    return result;
  }
  // 更新动态
  async update(content, momentId) {
    const statement = `UPDATE moment SET content = ? WHERE id = ?;`
    const [result] = await connection.execute(statement, [content, momentId]);
    return result;
  }
  // 删除动态
  async remove(momentId) {
    const statement = `DELETE FROM moment WHERE id = ?;`
    const [result] = await connection.execute(statement, [momentId]);
    return result;
  }

}
module.exports = new MomentService()